<template>
    <!-- 待签署合同 -->
    <div class="gd-main" style="background-color:#fff;z-index:100;">
        <div class="clearfix">
            <el-tag style="font-size:20px;height:40px;line-height:38px;">{{projectName}}</el-tag>
        </div>
        <!-- table表格 -->
        <!-- 
            @表格配置
                1. <el-table> 标签
                    1.1 :data - "tableData"
                        1.1.1 tableData 为对象数组，拿到服务器器的数据进行赋值
                        1.1.2 tableData 要在 data() 方法返回的 对象里配置，初始值设置为 [] 空数组
                2. <el-table-column> 标签
                    2.1 prop - "projectName" 列的属性名， tableData 里的对象的属性 
                    2.2 lable - "项目" 列的名称
                    2.3 width - "360" 列的宽度
        -->
        <!-- 
            height: 100vh   - 70px(面包屑+底部滚动条) 
                            - 20px(上内填充)
                            - 40px(标签)
                            - 20px(表格上外间距)
                            -52px(底部页码)
        -->
        <el-table style="margin-top:20px;" :data="tableData" height="calc(100vh - 202px)">
            <el-table-column prop="contractId" label="合同工编号" width="270"></el-table-column>
            <el-table-column prop="partyBName" label="班组长" width="220"></el-table-column>
            <el-table-column prop="contractStatus" label="状态" width="120">
                <template slot-scope="scope">
                        {{scope.row.contractStatus | contractStatus}}
                </template>
            </el-table-column>
            <el-table-column prop="detailsTimeInfo.createTime" label="发起日期" width="160"></el-table-column>
            <el-table-column width="200" label="操作">
                <template slot-scope="scope">
                    <!-- 事件定义 -->
                    <!--
                        事件声明: @click - "detail(scope.row)"
                        click - 事件类型
                        detail - click事件函数, 可传递的参数 scope.row,scope.column,scope.$index,scope.store
                    -->
                    <el-button type="text" @click="detail(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!--
            @分页配置
                :total - pagination.total 总条数
                :pager-count="7"显示的页码按钮数量, 大于等于 5 <= 21 基数
                :current-page = "pagination.currentPage" 当前的选中的页码
                :page-size="10" 每页显示的条目数
                :page-sizes="" 可选则的每页显示的条目数
                layout="total, sizes, prev, pager, next, jumper" 显示的元素
                @size-change="handleSizeChange"  - handleSizeChange 每页的条数改变时触发，参数为选择的条数
                @current-change="handleCurrentChange" - handleCurrentChange methods 配置 参数为点击的页码，或者输入的页码  
        -->
        <el-pagination 
            style="margin-top:20px;" 
            :total="pagination.total"
            :pager-count="pagination.pageCount"
            :current-page="pagination.currentPage" 
            :page-sizes="pagination.pageSizes" 
            :page-size="pagination.pageSize" 
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            >
        </el-pagination>
        <!-- pdf 预览 -->
        <pdf-view v-show="showpdf" :topoffset="60" :pdfurl="pdfurl">
            <!-- 顶部栏的内容 -->
            <el-row :gutter="20" style="text-align:center;padding:20px;position:absolute;left:0;top:0;right:0;background-color:#fff;">
                <div>
                    <span style="margin:0 20px;">{{projectName}}</span>
                    <span style="margin:0 100px 0 20px;">合同编号: {{contractId}}</span>
                     <!-- 取消合同按钮 -->
                    <el-button @click="clickCancelContract" type="primary">取消合同</el-button>
                    <!-- 签订合同按钮 -->
                    <el-button @click="clickSignContract" type="primary">签订合同</el-button>
                    <!-- 返回按钮 -->
                    <el-button @click="closePreview">返回</el-button>
                </div>
            </el-row>
            <div class="enclosureBox">
                <div style="text-align:center">
                    <el-tag style="font-size:16px;margin:20px auto">附件下载列表</el-tag>    
                </div>
                <span style="display:inline-block;color:red;font-size:12px;padding:0 20px;">提示:点击后，在新打开的窗口右键保存</span>
                <a class="download" 
                    target="_blank"
                    v-for="item in enclosure" 
                    :href="item.enclosureUrl" 
                    :download="item.enclosureName">{{item.enclosureName}}</a>
            </div>
        </pdf-view>
        <el-dialog width="500px" title="身份验证" :modal="false" :visible.sync="dialogFormVisible">
            <el-form 
                :rules="rules"
                ref="form" 
                :model="form" 
                label-position="left">
                <!-- 手机号 -->
                <el-form-item prop="phoneNumber" style="margin-bottom:20px !important;">
                    <el-input v-model="form.phoneNumber" placeholder="请输入手机号"></el-input>   
                </el-form-item>
                <!-- 验证码 -->
                <el-form-item prop="yzm" style="margin-bottom:20px !important;">
                    <el-row>
                        <el-col :span="17">
                            <el-input v-model="form.yzm" placeholder="请输入验证码"></el-input>
                        </el-col>
                        <el-col :span="6" :push="1"><el-button style="width:100%;" :disabled="btnDisabled" @click="clickGetYzm" type="primary">{{btnYzmMsg}}</el-button></el-col>
                    </el-row>
                </el-form-item>
                <el-button style="width:100%;" type="primary" @click="onSubmit('form')">确定</el-button>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import {mapGetters} from 'vuex';
    //引入 ajax 请求的方法
    import {teamContract,contractDetail,cancelContract,signContract,getYzm,valideYzm,contractEnclosureFile} from '@/request/team';
    //引入 pdf预览组件
    import pdfView from '@/views/contract/components/pdfViewIframe';
    
    export default {
        //存储 projectId
        beforeRouteEnter(to,from,next){
            next(vm => {
                vm.projectId = vm.$route.query.projectId;
                vm.projectName = vm.$route.query.projectName;
                vm.teamContract();
            });
        },
        components:{
            pdfView  
        },
        // 页面上需要展示的数据都要在 [data方法] 的 return 语句返回的对象里存在声明，否则会报错 
        data() {
            return {
                contractId:'',
                //显示签订合同弹窗
                dialogFormVisible:false,
                showpdf:false,
                pdfurl:'',
                //附件
                enclosure:[],
                //表单数据 - 项目名称
                form:{
                    phoneNumber: '',
                    yzm: ''
                },
                //表单验证规则 [ 也可以自己配置验证规则 ]
                rules:{
                    //项目名称验证
                    phoneNumber:[
                        {required:true,message:'请输入手机号码',trigger:'change'},
                        {pattern:/\d{11}/,message:'请输入11位手机号码',trigger:'change'},
                    ],
                    //项目状态验证
                    yzm:[{required:true,message:'请输入验证码',trigger:'change'}]
                },
                btnYzmMsg:'获取验证码',
                btnDisabled:false,
                cid:'',
                //项目数量
                projectId:'',
                projectName:'',
                tableData: []
            }
        },
        computed:{
            //登录后的数据在这里进行给实例赋值，就可以用 this.xxx 进行访问了
          ...mapGetters(['userId','currId','roleId','verificationStatus'])  
        },
        methods: {
            onSubmit(formRef){
                this.$refs[formRef].validate(validate => {
                    if(validate){
                        //验证码验证
                        this.valideYzm({
                            phone:this.form.phoneNumber,
                            code:this.form.yzm
                        }).then(() => {
                            //验证码验证成功 - 签署合同
                            this.signContract({
                                contractId:this.contractId,
                                userId:this.userId,
                                currId:this.currId,
                                roleId:this.roleId,
                                phone:this.form.phoneNumber,
                                signCode:this.form.yzm,
                                originatorType:1
                            });
                        });
                    }
                });
            },
            //获取验证码接口
            clickGetYzm(){
                this.$refs.form.validateField('phoneNumber',errMsg => {
                    //验证通过
                    if(errMsg === ''){
                        //禁用发送按钮
                        this.disabledBtn();
                        let queryObj = {
                            eomType:1,
                            phone:this.form.phoneNumber
                        };
                        this.getYzm(queryObj);
                    }
                });
            },
            disabledBtn(){
                this.btnDisabled = true;
                let time = 60;
                this.cid = setInterval(() => {
                    time--;
                    this.btnYzmMsg = time + 's'
                    if(time <= 0){
                        clearInterval(this.cid);
                        this.btnDidsabled = false;
                        this.btnYzmMsg = '获取验证码';
                    }
                },1000);
            },
            //手机验证码验证
            valideYzm(queryObj){
                return valideYzm(queryObj).then(res => {
                    console.log('验证码验证:',res);
                    if(res.data.respCode != '1'){
                        this.$message({
                            message: res.data.entry.respMsg,
                            type: 'error',
                            duration: 3 * 1000
                        });
                        return Promise.reject(res.data.entry.respMsg);    
                    }
                });
            },
            //获取验证码
            getYzm(queryObj){
                return getYzm(queryObj).then(res => {
                    if(res.data.respCode == '1'){
                        this.$message({
                            type:'success',
                            message:res.data.entry.respMsg
                        });
                    }else{
                        this.$message({
                            message: res.data.entry.respMsg,
                            type: 'error',
                            duration: 3 * 1000
                        });
                        //返回错误信息
                        return Promise.reject(res.data.entry.respMsg);
                    }
                }).catch(error => {
                    this.$message({
                        message: error.message,
                        type: 'error',
                        duration: 3 * 1000
                    });
                    //返回错误信息
                    return Promise.reject(error.message);
                });
            },
            //关闭 pdf 预览
            closePreview(){
                this.showpdf = false;
                this.dialogFormVisible = false;
            },
            //取消合同
            clickCancelContract(curRow){
                //关闭弹窗
                this.closePreview();
                this.cancelContract({
                    contractId:this.contractId,
                    userId:this.userId
                });
            },
            //签订合同
            clickSignContract(){
                this.dialogFormVisible = true;
            },
            //切换每页显示的数量量
            handleSizeChange(pageSize) {
                console.log('每页显示' + pageSize + '条数据');
                this.pagination.pageSize = pageSize;
                this.teamContract({limit:pageSize});
            },
            //选中的页码
            handleCurrentChange(currentPage) {
                console.log('点击了第 ' + currentPage + '页');
                this.pagination.currentPage = currentPage;
                this.teamContract({page:currentPage});
            },
            //查看详情
            detail(curRow){
                this.contractId = curRow.contractId;
                let params = {
                    contractId:curRow.contractId
                };
                this.contractDetail(params);
                //查询附件
                this.contractEnclosureFile(params);
            },
            // 接口6：签署合同
            signContract(queryObj){
                return signContract(queryObj).then(res => {
                    this.$message({
                        type:'success',
                        message:res.msg
                    });
                    //隐藏 el-dialog
                    this.dialogFormVisible = false;
                    this.showpdf = false;
                    //清除校验结果
                    this.$refs.form.clearValidate();
                    //置空手机号和验证码
                    this.form.phoneNumber = '';
                    this.form.yzm = '';
                    //清除按钮禁用文字清除倒计时
                    clearInterval(this.cid);
                    this.btnDidsabled = false;
                    this.btnYzmMsg = '获取验证码';
                    
                    //重新查询数据
                    this.teamContract();
                });
            },
            // 接口7：取消合同
            cancelContract(queryObj){
                return cancelContract(queryObj).then(res => {
                    this.$message({
                        message:res.msg,
                        type:'success'
                    });
                    //刷新数据
                    this.teamContract();
                });
            },
            //合同详情
            contractDetail(queryObj){
                return contractDetail(queryObj).then(res => {
                    console.log('合同:',res);
                    /*this.pdfurl = 'http://192.168.1.227:9696/test.pdf';*/
                    this.pdfurl = res.data.result[0].detailsUrlInfo.sourceContractUrl;
                    //合同编号
                    this.contractId = res.data.result[0].contractId;
                    this.showpdf = true;
                });
            },
            // 接口9：待签订班组合同
            teamContract(queryObj = {}){
                /*
                    @param
                            queryObj 用来动态替换查询参数
                            
                */
                let params = { 
                    userId:this.userId,
                    //当前页
                    page:this.pagination.currentPage,
                    //每页显示的条数
                    limit:this.pagination.pageSize,
                    //合同状态 - 待签订
                    contractType:-1,
                    //工程 id
                    projectId:this.projectId,
                    //合同类型 - 班组
                    originatorType:1,
                    //请求类型 - 分包
                    sourceType:1
                };
                //参数进行动态拷贝
                Object.assign(params,queryObj);
                return teamContract(params).then(res => {
                    //列表数据
                    this.tableData = res.data.result || [];
                    //分页总数据
                    this.pagination.total = res.data.resultTotal || 0;
                });
            },
            //查询附件
            contractEnclosureFile(queryObj){
                return contractEnclosureFile(queryObj).then(res => {
                    console.log('附件列表',res); 
                    this.enclosure = res.data || [];
                });
            }
        }
    }
</script>

<style lang="less" scoped>
.download{
    display:block;margin:0 10px;
    font-size:14px;height:40px;line-height:40px;
}

.enclosureBox{
    width:200px;height:100%;position:absolute;z-index:100;
    right:0;top:80px;bottom:0;background-color:#ddd;
    
}
</style>
